#include "common.h"
#include "NesGamePad.h"
#include <cassert>

NesGamePad::NesGamePad()
{
	mGamepadIndex_1 = 0;
	mGamepadIndex_2 = 0;
}

void NesGamePad::UserInput(uint8_t index, unsigned state)
{
	if (index >= 0 && index < 16)
		this->mGamepadStatus[index] = state;
}

void NesGamePad::WriteRegViaCpu(uint16_t address, uint8_t data)
{
	switch (address) {
	case 0x4016: {
		if (data & 1) {
			mGamepadEn = 1;
			mGamepadIndex_1 = 0;
			mGamepadIndex_2 = 0;
		}
		else
			mGamepadEn = 0;
		break;
	}
	}
}

uint8_t NesGamePad::ReadRegViaCpu(uint16_t address)
{
	uint8_t data = 0;
	switch (address) {
	case 0x4016:
		if (mGamepadEn == 0)
		{
			data = mGamepadStatus[mGamepadIndex_1 % 8] | 0x40;
			mGamepadIndex_1++;
		}
		break;
	case 0x4017:
		if (mGamepadEn == 0)
		{
			data = mGamepadStatus[8 + mGamepadIndex_2 % 8];
			mGamepadIndex_2++;
		}
		break;
	}
	return data;
}

void NesGamePad::Reset()
{
	 mGamepadEn = 0;
	 mGamepadIndex_1 = 0;
	 mGamepadIndex_2 = 0;
	 memset(mGamepadStatus,0,sizeof(mGamepadStatus));
}

void NesGamePad::Save(SaveBundle* bundle)
{
	bundle->SaveByte(mGamepadEn);
	bundle->SaveByte(mGamepadIndex_1);
	bundle->SaveByte(mGamepadIndex_2);
}

void NesGamePad::Restore(SaveBundle* bundle)
{
	mGamepadEn = bundle->RestoreByte();
	mGamepadIndex_1 = bundle->RestoreByte();
	mGamepadIndex_2 = bundle->RestoreByte();
}
